package com.steven.test.exception;

import com.steven.test.enums.ResponseEnum;
import com.steven.test.web.response.ResponseData;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局controller层异常处理
 *
 * @author qinxh
 * @date 2019/08/22
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 拦截所有异常，可以自己根据需求设定范围
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object exceptionHandler(Exception e){

        // 自定义全局异常（TIPS：返回格式为统一返回结果集）
        if (e instanceof GlobalException) {
            GlobalException globalException = (GlobalException) e;
            logger.error("GlobalException is {}，e:\n{}", globalException.geResponseEnum().getMessage(), e);
            return ResponseData.ofStatus(globalException.geResponseEnum());
        }
        // 自定义全局异常（TIPS：返回为指定视图）
        if (e instanceof GlobalViewException){
            ModelAndView model = new ModelAndView("/500");
            model.addObject("msg", e.getMessage());
            return model;
        }
        // 上传文件异常
        if(e instanceof MultipartException){
            logger.error("MultipartException is {}，e:\n{}",e.getMessage(),e);
        	return ResponseData.ofMessage(ResponseEnum.MULTIPART_ERROR.getCode(), e.getCause().getMessage());
        }
        // 除此之外，统归为系统异常
        logger.error("ServerException is {}，e:\n{}", ResponseEnum.SERVER_ERROR.getMessage(), e);
        return ResponseData.ofStatus(ResponseEnum.SERVER_ERROR);

    }
}